// 检查用户是否已登录
function checkAuth() {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'index.html';
        return;
    }
    return token;
}

// 获取用户信息
async function loadUserData() {
    const token = checkAuth();
    if (!token) return;

    try {
        const response = await fetch('http://localhost:3000/api/dashboard', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        if (response.ok) {
            const data = await response.json();
            updateDashboard(data);
        } else {
            // Token无效，清除并跳转登录页
            localStorage.removeItem('token');
            window.location.href = 'index.html';
        }
    } catch (error) {
        console.error('获取用户数据失败:', error);
        showError('获取数据失败，请刷新页面重试');
    }
}

// 更新仪表板数据
function updateDashboard(data) {
    const { user, data: dashboardData } = data;
    
    document.getElementById('userName').textContent = user.name;
    document.getElementById('welcomeMessage').textContent = `欢迎回来，${user.name}！`;
    document.getElementById('userId').textContent = user.id;
    document.getElementById('lastLogin').textContent = dashboardData.lastLogin;
    document.getElementById('totalVisits').textContent = dashboardData.totalVisits;
    
    // 更新当前时间
    updateCurrentTime();
}

// 更新当前时间
function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    document.getElementById('currentTime').textContent = timeString;
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    window.location.href = 'index.html';
}

// 刷新数据
function refreshData() {
    loadUserData();
    showMessage('数据已刷新');
}

// 查看个人资料
function viewProfile() {
    showMessage('个人设置功能开发中...');
}

// 修改密码
function changePassword() {
    showMessage('修改密码功能开发中...');
}

// 查看帮助
function viewHelp() {
    showMessage('帮助中心功能开发中...');
}

// 显示消息
function showMessage(text) {
    const message = document.createElement('div');
    message.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #27ae60;
        color: white;
        padding: 1rem 2rem;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 1000;
    `;
    message.textContent = text;
    document.body.appendChild(message);
    
    setTimeout(() => {
        message.remove();
    }, 3000);
}

// 显示错误
function showError(text) {
    const message = document.createElement('div');
    message.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #e74c3c;
        color: white;
        padding: 1rem 2rem;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 1000;
    `;
    message.textContent = text;
    document.body.appendChild(message);
    
    setTimeout(() => {
        message.remove();
    }, 3000);
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadUserData();
    
    // 每分钟更新一次当前时间
    setInterval(updateCurrentTime, 1000);
    
    // 每30秒刷新一次数据
    setInterval(() => {
        loadUserData();
    }, 30000);
});

// 防止返回登录页
window.addEventListener('pageshow', function(event) {
    if (event.persisted) {
        checkAuth();
    }
});